﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;

using SysBinaryFormatter = System.Runtime.Serialization.Formatters.Binary.BinaryFormatter;

namespace Titan.Serialization
{
    public class BinaryFormatter : IFormatter
    {
        private SysBinaryFormatter _formatter;
        private ISurrogateSelector _selector;
        private ISurrogateSelector _dataSetSelector;
        private ISurrogateSelector _dataTableSelector;

        public BinaryFormatter()
        {
            _formatter = new SysBinaryFormatter();
            _dataSetSelector = new DataSetSurrogateSelector();
            _dataTableSelector = new DataTableSurrogateSelector();
            _dataSetSelector.ChainSelector(_dataTableSelector);
        }

        public SerializationBinder Binder
        {
            get { return _formatter.Binder; }
            set { _formatter.Binder = value; }
        }

        public StreamingContext Context
        {
            get { return _formatter.Context; }
            set { _formatter.Context = value; }
        }

        public object Deserialize(Stream serializationStream)
        {
            return _formatter.Deserialize(serializationStream);
        }

        public void Serialize(Stream serializationStream, object graph)
        {
            _formatter.Serialize(serializationStream, graph);
        }

        public ISurrogateSelector SurrogateSelector
        {
            get { return _selector; }
            set { _selector = value; _dataTableSelector.ChainSelector(_selector); }
        }
    }
}
